/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import cn.hutool.db.sql.Direction;
import me.zhengjie.modules.biz.domain.Announcement;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.AnnouncementRepository;
import me.zhengjie.modules.biz.service.AnnouncementService;
import me.zhengjie.modules.biz.service.dto.AnnouncementDto;
import me.zhengjie.modules.biz.service.dto.AnnouncementQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.AnnouncementMapper;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-17
**/
@Service
@RequiredArgsConstructor
public class AnnouncementServiceImpl implements AnnouncementService {

    private final AnnouncementRepository announcementRepository;
    private final AnnouncementMapper announcementMapper;

    @Override
    public Map<String,Object> queryAll(AnnouncementQueryCriteria criteria, Pageable pageable){
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getType() != null) {
                predicates.add(criteriaBuilder.equal(root.get("type"),  criteria.getType()));
            }

            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);

        return PageUtil.toPage(page.map(announcementMapper::toDto));
    }

    @Override
    public List<AnnouncementDto> queryAll(AnnouncementQueryCriteria criteria){
        return announcementMapper.toDto(announcementRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AnnouncementDto findById(Integer id) {
        Announcement announcement = announcementRepository.findById(id).orElseGet(Announcement::new);
        ValidationUtil.isNull(announcement.getId(),"Announcement","id",id);
        return announcementMapper.toDto(announcement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AnnouncementDto create(Announcement resources) {
        return announcementMapper.toDto(announcementRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Announcement resources) {
        Announcement announcement = announcementRepository.findById(resources.getId()).orElseGet(Announcement::new);
        ValidationUtil.isNull( announcement.getId(),"Announcement","id",resources.getId());
        announcement.copy(resources);
        announcementRepository.save(announcement);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            announcementRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AnnouncementDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AnnouncementDto announcement : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("公告标题", announcement.getName());
            map.put("公告内容", announcement.getContent().substring(3, announcement.getContent().length() - 4));
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    public AnnouncementDto queryPlatformIntro() {

        Announcement announcement = announcementRepository.findByType(1);
        return announcementMapper.toDto(announcement);
    }


    public Map<String, Object> queryAnnouncementList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification =  (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 2));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));
    }

    public Map<String, Object> queryNewsList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 3));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));
    }

    public Map<String, Object> queryRulesList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 4));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));
    }

    public Map<String, Object> queryChargeList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 5));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));
    }

    @Override
    public AnnouncementDto queryAnnouncementListDetail(Integer id) {
        Announcement announcement = announcementRepository.findById(id).orElseGet(Announcement::new);
        return announcementMapper.toDto(announcement);
    }

    @Override
    public Map<String, Object> queryAnnouncmentList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getContent() != null){
                predicates.add(criteriaBuilder.like(root.get("content"), "%" + criteria.getName() + "%"));
            }
            predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 2)), (criteriaBuilder.equal(root.get("type").as(Integer.class), 4))));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));
    }

    @Override
    public Map<String, Object> queryPolicyList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getContent() != null){
                predicates.add(criteriaBuilder.like(root.get("content"), "%" + criteria.getContent() + "%"));
            }
            predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 2))));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));    }

    @Override
    public Map<String, Object> queryRuleList(AnnouncementQueryCriteria criteria, Pageable pageable) {
        Specification<Announcement> specification = (Specification<Announcement>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + criteria.getName() + "%"));
            }
            if (criteria.getContent() != null){
                predicates.add(criteriaBuilder.like(root.get("content"), "%" + criteria.getContent() + "%"));
            }
            predicates.add(criteriaBuilder.or((criteriaBuilder.equal(root.get("type").as(Integer.class), 4))));
            query.where(predicates.toArray(new Predicate[predicates.size()]));
            query.orderBy(criteriaBuilder.asc(root.get("order")));

            return query.getRestriction();
        };
        Page<Announcement> page = announcementRepository.findAll(specification, pageable);
        return PageUtil.toPage(page.map(announcementMapper::toDto));    }
}
